﻿Imports System.Runtime.CompilerServices
Imports System.Net
Imports System.Text
Imports System.Web
Imports System.Collections.Specialized

Friend Module WebClientExtension
    ''' <param name="queryString">この内容はURLエンコードされます</param>
    <Extension()> _
    Public Function HttpGet(ByVal webClient As WebClient, ByVal url As String, ByVal queryString As NameValueCollection, ByVal userID As String, ByVal userPass As String) As String
        Dim res As String = ""
        Using client As New WebClient()
            client.Encoding = Encoding.UTF8

            client.Credentials = New NetworkCredential(userID, userPass)

            For i As Integer = 0 To queryString.Keys.Count - 1
                queryString(queryString.Keys(i)) = HttpUtility.UrlEncode(queryString(queryString.Keys(i)))
            Next
            client.QueryString = queryString

            Try
                res = client.DownloadString(url)
            Catch ex As WebException
                Throw New WebException("通信エラー", ex)
            End Try
        End Using

        Return res
    End Function

    ''' <param name="valus">この内容はURLエンコードされます</param>
    <Extension()> _
    Public Function HttpPost(ByVal webClient As WebClient, ByVal url As String, ByVal valus As NameValueCollection, ByVal userID As String, ByVal userPass As String) As String
        Dim url_ As String = url
        If valus.Count >= 1 Then
            url_ += "?"
        End If

        Dim res() As Byte = Nothing
        Using client As New WebClient()
            client.Encoding = Encoding.UTF8

            client.Credentials = New NetworkCredential(userID, userPass)

            For Each key As String In valus.Keys
                url_ += key + "=" + HttpUtility.UrlEncode(valus(key)) + "&"
            Next

            Try
                res = client.UploadData(url_, System.Text.Encoding.Default.GetBytes(""))
            Catch ex As WebException
                 Throw New WebException("通信エラー", ex)
            End Try
        End Using
        Return Encoding.UTF8.GetString(res)
    End Function

End Module